package findzip

import (
	"archive/zip"
	"bytes"
	"encoding/json"
	"flag"
	"io/fs"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strconv"
	"strings"
)

func Wail(path string, info fs.FileInfo, err error) error {
	if info.IsDir() {
		return nil
	}

	if strings.HasSuffix(strings.ToLower(path), ".zip") {
		if Find(path, flag.Arg(1)) {
			log.Println(path)
			base := filepath.Base(path)
			os.Rename(path, filepath.Join("/home/ender/文档/2020", base))
		}
	}

	return nil
}

func Find(path, str string) bool {
	rc, err := zip.OpenReader(path)
	if err != nil {
		return false
	}

	defer rc.Close()

	key := []byte(str)

	for _, file := range rc.File {
		f, err := file.Open()
		if err != nil {
			return false
		}

		defer f.Close()

		bs := make([]byte, 1024)
		for {
			i, err := f.Read(bs)
			if err != nil {
				break
			}

			if bytes.Contains(bs[:i], key) {
				return true
			}
		}
	}

	return false
}

func WailJSON(path string, info fs.FileInfo, err error) error {
	if info.IsDir() {
		return nil
	}

	if strings.HasSuffix(strings.ToLower(path), ".zip") {
		if PathExists(path + ".json") {
			return nil
		}

		if err := JSON(path, flag.Arg(1)); err != nil {
			log.Fatalln(err)
		}
	}

	return nil
}

func JSON(path, str string) error {
	log.Println(path, str)

	float, _ := strconv.ParseFloat(str, 64)
	rc, err := zip.OpenReader(path)
	if err != nil {
		return err
	}

	defer rc.Close()

	for _, file := range rc.File {
		f, err := file.Open()
		if err != nil {
			return err
		}

		defer f.Close()

		bs, err := ioutil.ReadAll(f)
		if err != nil {
			return err
		}
		m := []map[string]interface{}{}
		if err := json.Unmarshal(bs, &m); err != nil {
			return err
		}

		n := []map[string]interface{}{}
		for _, p := range m {
			if p["hx_seller_id"].(float64) == float {
				n = append(n, p)
			}
		}

		if len(n) == 0 {
			continue
		}

		log.Println("保存json:", len(n))

		js, err := json.Marshal(n)
		if err != nil {
			log.Fatalln(err)
		}

		file, err := os.Create(path + ".json")
		if err != nil {
			log.Fatalln(err)
		}
		defer file.Close()

		file.Write(js)
	}

	return nil
}
